<?php
/**
 * Created by PhpStorm.
 * User: chl
 * Date: 2017/3/16 0016
 * Time: 11:53
 */
namespace app\admin\controller;
use app\models\Bases;
use think\Db;
use think\Request;

class Admin extends Base{
    public function adminList(){
        $adminModel = new Bases('admin');
        try{
            $join = [
                ['auth_group_access c','a.id=c.uid','left'],
                ['auth_group b' ,'c.group_id = b.id','left'],
            ];
            $fields = "a.*,b.title";
            $where['a.id']=['>',1];
            $result['list'] = $adminModel->joinData('a',$join,$where,$fields);
            $result['count'] = count($result['list']);
        }catch(\Exception $e){
            return self::formatResult($e->getCode(),$e->getMessage());
        }
        return view('adminList',['result'=>$result]);
    }

    public function adminAdd(){
        $auth = new Bases('auth_group_access');
        $admin = new Bases('admin');
        $authGroup = new Bases('auth_group');
        try{
            if(Request()->isPost()){
               $post = input('param.');
                $validate = $this->validate($post,'Admin.adminAdd');//验证
                if($validate !== true){
                    throw new \LogicException($validate,10000);
                }
                $post['password'] = password_hash($post['password'],true);
                $post['create_time'] = time();
                $roleId = $post['role_id'];
                unset($post['pwds']);
                unset($post['role_id']);
                Db::startTrans();
                $admin_id = $admin->insertData($post);
                $data['uid'] = $admin_id;
                $data['group_id'] = $roleId;
                if(Db::name('auth_group_access')->insert($data) && $admin_id){
                    Db::commit();
                    /*========================添加日志========================*/
                    $adminInfo = $admin->find('id ='.$admin_id);
                    $str = "添加".$adminInfo['username']."后台账号";
                    // 向日志表插入记录
                    $admin->addAdminLog($str);
                    /*========================================================*/
                    return self::formatSuccessResult();
                } else{
                    Db::rollback();
                }
            }
        }catch(\Exception $e){
            return self::formatResult($e->getCode(),$e->getMessage());
        }
        //获取所有角色信息
        $where['id'] = ['<>',1];
        $where['status'] = ['=',1];
        $result  = $authGroup->selectData($where);
        return view('adminAdd',['result'=>$result]);
    }

    public function adminSave(){
        $adminModel = new Bases('admin');
        $authGroup = new Bases('auth_group');
        $auth = new Bases('auth_group_access');
        $id = intval(input('id'));
        $join = [
            ['auth_group_access c','a.id=c.uid','left'],
            ['auth_group b' ,'c.group_id = b.id','left'],
        ];
        try{
            if(Request()->isPost()){
                $post = input('param.');
                $username = $post['username'];
                $id = intval($post['id']);
                $groupId = $post['group_id'];
                $rs  = $adminModel->updateData(['username'=>$username],['id'=>$id]);
                $rs1 = $auth->updateData(['group_id'=>$groupId],['uid'=>$id]);
                if($rs !== false && $rs1 !== false){
                    /*========================添加日志========================*/
                    $adminInfo = $adminModel->find('id ='.$id);
                    $str = "修改".$adminInfo['username']."后台账号";
                    // 向日志表插入记录
                    $adminModel->addAdminLog($str);
                    /*========================================================*/
                    return self::formatSuccessResult();
                }return self::formatResult(406,'操作失败');
            }
        }
        catch(\Exception $e){
            return self::formatResult($e->getCode(),$e->getMessage());
        }
        $where['a.id'] = ['=',$id];
        $fields = " a.*,b.id as role_id";
        $where1['id'] = ['<>',1];
        $where1['status'] = ['=',1];
        $adminInfo = $adminModel->joinData('a',$join,$where,$fields);
        $roleInfo  = $authGroup->selectData($where1);
        return view('adminSave',['adminInfo'=>$adminInfo,'roleInfo'=>$roleInfo]);
    }

    public function adminDelete(){
        $id = intval(input('id'));
        $adminModel = new Bases('admin');
        $authGroup = new Bases('auth_group_access');
        //在删除之前保存操作记录
        $adminInfo = $adminModel->find('id ='.$id);
        $str = "修改".$adminInfo['username']."后台账号";

        $rs = $adminModel->deleteByWhere(['id'=>$id]);
        $rs1= $authGroup->deleteByWhere(['uid'=>$id]);
        if($rs !== false && $rs1 !== false){
            /*========================添加日志========================*/
            // 向日志表插入记录
            $adminModel->addAdminLog($str);
            /*========================================================*/
            return self::formatSuccessResult();
        }return self::formatResult(406,'删除失败');
    }

    public function adminChangePassword(){
        $id = intval(input('id'));
        $adminModel = new Bases('admin');
        try{
            if(Request()->isPost()){
                $post = input('param.');
                $password = password_hash($post['password'],true);
                $rs = $adminModel->updateData(['password'=>$password],['id'=>intval($post['id'])]);
                if($rs !== false){
                    $adminInfo = $adminModel->find('id ='.intval($post['id']));
                    $str = "修改".$adminInfo['username']."后台账号密码";
                    $adminModel->addAdminLog($str);
                    return self::formatSuccessResult();
                }return self::formatResult(406,'操作失败');
            }
        }catch(\Exception $e){
            return self::formatResult($e->getCode(),$e->getMessage());
        }
        $adminInfo = $adminModel->find(['id'=>$id],'username,id');
        return view('changePassword',['adminInfo'=>$adminInfo]);
    }

    /**改变用户状态
     * @return array
     */
    public function adminStatusChange(){
        $status = input('status');
        $id = input('id');
        $status = $status==1 ? 2:1;
        $userModel = new Bases('admin');
        $rs = $userModel->updateData(['status'=>$status],'id = '.$id);
        if($rs !== false){
            return self::formatSuccessResult(['status'=>$status]);
        }return self::formatResult(406,'操作失败');

    }
}